package cn.formaggie.service.impl;

import cn.formaggie.dao.RolePermissionDao;
import cn.formaggie.service.face.BackManageService;
import cn.formaggie.service.face.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("rolePermissionService")
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    public Integer setDefaultPermission(Integer roleId) {
        return rolePermissionDao.addRolePermissionItem(roleId,6);
    }

    @Override
    public Boolean modifyRolePermission(Integer roleId, List<Integer> permissions) {
        List<Integer> oldPermissions=rolePermissionDao.getPermissionIdOfRole(roleId);
        if(oldPermissions.size()==0){
            for(Integer pId:permissions){
                rolePermissionDao.addRolePermissionItem(roleId,pId);
            }
            return true;
        }else{
            Map<Integer,Boolean> map=findModifyItem(oldPermissions,permissions);
            for(Integer p:map.keySet()){
                if(map.get(p)){
                    rolePermissionDao.addRolePermissionItem(roleId,p);
                }else{
                    rolePermissionDao.deleteRolePermissionItem(roleId,p);
                }
            }
            return true;
        }
    }

    @Override
    public Boolean deleteAllPermissionForRole(Integer roleId) {
        return rolePermissionDao.deleteAllPermissionForRole(roleId)>0?true:false;
    }

    private Map<Integer,Boolean> findModifyItem(List<Integer> old,List<Integer> newPermission){
        Map<Integer,Boolean> map=new HashMap<>();
        for(Integer p:newPermission){
            map.put(p,true);
        }
        for(Integer p:old){
            if(newPermission.contains(p)){
                map.remove(p);
            }else{
                map.put(p,false);
            }
        }
        return map;
    }
}
